package com.ruoyi.pay.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;

import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.pay.response.Result;
import com.ruoyi.pay.utils.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 */
//@RestController
//@RequestMapping("pay/alipay")
public class AliPayController {

    @Autowired
    IdWorker idWorker;

    @Autowired
    AlipayClient alipayClient;

    @PostMapping("genWorkerId")
    public AjaxResult genWorkerId() throws Exception {
        return new AjaxResult(200,"OK", String.valueOf(idWorker.nextId()));
    }

    /**
     *
     * @param out_trade_no 商户订单号，商户网站订单系统中唯一订单号，必填
     * @param total_amount 付款金额，必填
     * @param subject 订单名称，必填
     * @param body 商品描述，可空
     * @return
     * @throws AlipayApiException
     */
    @GetMapping(value = {
            "alipay_trade_page_pay/{out_trade_no}/{total_amount}/{subject}/{body}",
            "alipay_trade_page_pay/{out_trade_no}/{total_amount}/{subject}"
    })
    public AjaxResult alipay_trade_page_pay(
            @PathVariable String out_trade_no,
            @PathVariable Double total_amount,
            @PathVariable String subject,
            @PathVariable(required = false) String body
    ) throws AlipayApiException {
        //获得初始化的AlipayClient

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        //alipayRequest.setReturnUrl(AlipayConfig.return_url);
        //alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
/*

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = new String(request.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        //付款金额，必填
        String total_amount = new String(request.getParameter("WIDtotal_amount").getBytes("ISO-8859-1"),"UTF-8");
        //订单名称，必填
        String subject = new String(request.getParameter("WIDsubject").getBytes("ISO-8859-1"),"UTF-8");
        //商品描述，可空
        String body = new String(request.getParameter("WIDbody").getBytes("ISO-8859-1"),"UTF-8");
*/

        Map map = new HashMap<>();
        map.put("out_trade_no",out_trade_no);
        map.put("total_amount",total_amount);
        map.put("subject",subject);
        map.put("body",body);
        map.put("product_code","FAST_INSTANT_TRADE_PAY");
        String jsonString = JSON.toJSONString(map);
        /*alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");*/
        alipayRequest.setBizContent(jsonString);

        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

        /*
        <form name=\"punchout_form\" method=\"post\"
        action=\"https://openapi.alipaydev.com/gateway.do?charset=utf-8&method=alipay.trade.page.pay&sign=cDBpQe2BHrXBl1GSw4UHqq11DSHgcFrEkS9OSsO4AHSkfZB%2BF%2FZWzWdedch9cVd4SMjn0RiVJCOHSg0gdhA%2BK%2BFn5k2LGQfI1vjdpg1PeetgUSTBu%2F692Hltt599HaMbVd4vokyuqQFua4R%2BoVDGvAiJ4RDHoUjlgqsEoaNrAS8gCB691tItt%2FiaCzx9KodHYAhgKUoJGYBKk7jFxurrudD0fzHS4X97dRWtpLIQpZXHLnMeomqa77HKROW6G6xrwffQLDqvS6JoCDm8a3hqc%2FmimHmUdwwvxfYNSn8d1v6M4T4PvTeT8Dpc4U0lN4nmnje3HdCHQRhdgoMFHFeBDg%3D%3D&version=1.0&app_id=2016101900726103&sign_type=RSA2&timestamp=2022-11-29+15%3A59%3A41&alipay_sdk=alipay-sdk-java-dynamicVersionNo&format=json\">\n<input type=\"hidden\" name=\"biz_content\" value=\"{&quot;out_trade_no&quot;:&quot;2022112915399657&quot;,&quot;total_amount&quot;:100.0,&quot;subject&quot;:&quot;hello&quot;,&quot;product_code&quot;:&quot;FAST_INSTANT_TRADE_PAY&quot;}\">\n<input type=\"submit\" value=\"立即支付\" style=\"display:none\" >\n</form>\n<script>document.forms[0].submit();</script>
         */
        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        System.out.println(result);

        return new AjaxResult(200,"OK",result);
    }

    @GetMapping(value = {
            "alipay_trade_query/{out_trade_no}"
    })
    public AjaxResult alipay_trade_query(@PathVariable String out_trade_no) throws AlipayApiException {
        //获得初始化的AlipayClient
        //设置请求参数
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();

        Map map = new HashMap();
        map.put("out_trade_no",out_trade_no);

        String jsonString = JSON.toJSONString(map);
        alipayRequest.setBizContent(jsonString);
        //请求
        String result = alipayClient.execute(alipayRequest).getBody();

        System.out.println(result);
        Map mapResult = JSON.parseObject(result, Map.class);
        String alipay_trade_query_response = mapResult.get("alipay_trade_query_response").toString();
        Map alipay_trade_query_response_map = JSON.parseObject(alipay_trade_query_response, Map.class);
        /*
        交易状态：WAIT_BUYER_PAY（交易创建，等待买家付款）、
                TRADE_CLOSED（未付款交易超时关闭，或支付完成后全额退款）、
                TRADE_SUCCESS（交易支付成功）、
                TRADE_FINISHED（交易结束，不可退款）
         */
        String code = (String)alipay_trade_query_response_map.get("code");
        if(code.equalsIgnoreCase("10000")){//10000成功
            String trade_status = (String)alipay_trade_query_response_map.get("trade_status");
            String trade_status_msg ="";
            switch (trade_status){
                case "TRADE_SUCCESS":
                    trade_status_msg="交易支付成功";
                    break;
                case "TRADE_CLOSED":
                    trade_status_msg="未付款交易超时关闭";
                    break;
                case "WAIT_BUYER_PAY":
                    trade_status_msg="交易创建，等待买家付款";
                    break;
                case "TRADE_FINISHED":
                    trade_status_msg="交易结束，不可退款";
                    break;

            }
            return new AjaxResult(200,"OK",trade_status_msg);
        }else{
            String sub_msg = (String)alipay_trade_query_response_map.get("sub_msg");
            return new AjaxResult(200,"OK",sub_msg);
        }
    }
}
